export default {
  mounted(el) {
    let isDragging = false;
    let startX, startY, initialX, initialY;

    // 通用坐标获取函数
    const getCoordinates = (e) => {
      if (e.type.startsWith('touch')) {
        return {
          x: e.touches[0].clientX,
          y: e.touches[0].clientY
        };
      } else {
        return {
          x: e.clientX,
          y: e.clientY
        };
      }
    };

    // 开始拖拽
    const startDrag = (e) => {
      isDragging = true;
      const coords = getCoordinates(e);
      
      // 记录初始位置
      initialX = el.offsetLeft;
      initialY = el.offsetTop;
      
      // 计算初始点击位置差值
      startX = coords.x - el.offsetLeft;
      startY = coords.y - el.offsetTop;

      // 添加样式
      el.style.transition = 'none';  // 拖拽时禁用过渡动画
      el.style.cursor = 'grabbing';

      // 阻止默认行为（重要：避免移动端页面滚动）
      e.preventDefault();
    };

    // 拖拽中
    const duringDrag = (e) => {
      if (!isDragging) return;
      
      const coords = getCoordinates(e);
      
      // 计算新位置
      let newX = coords.x - startX;
      let newY = coords.y - startY;

      // 边界限制
      const maxX = window.innerWidth - el.offsetWidth;
      const maxY = window.innerHeight - el.offsetHeight;
      
      newX = Math.max(0, Math.min(newX, maxX));
      newY = Math.max(0, Math.min(newY, maxY));

      // 应用新位置
      el.style.left = `${newX}px`;
      el.style.top = `${newY}px`;
    };

    // 结束拖拽
    const stopDrag = () => {
      isDragging = false;
      el.style.cursor = 'grab';
      el.style.transition = 'all 0.3s ease';  // 恢复过渡效果
    };

    // 事件绑定
    el.addEventListener('mousedown', startDrag);
    el.addEventListener('touchstart', startDrag, { passive: false });

    document.addEventListener('mousemove', duringDrag);
    document.addEventListener('touchmove', duringDrag, { passive: false });

    document.addEventListener('mouseup', stopDrag);
    document.addEventListener('touchend', stopDrag);

    // 移除事件监听（重要：避免内存泄漏）
    el._dragCleanup = () => {
      el.removeEventListener('mousedown', startDrag);
      el.removeEventListener('touchstart', startDrag);
      document.removeEventListener('mousemove', duringDrag);
      document.removeEventListener('touchmove', duringDrag);
      document.removeEventListener('mouseup', stopDrag);
      document.removeEventListener('touchend', stopDrag);
    };
  },

  beforeUnmount(el) {
    // 组件卸载时清理事件
    el._dragCleanup && el._dragCleanup();
  }
};